#include"tcp_ser.hpp"
#define Judge(x) if(x<0){return 0;}
using namespace std;
map<string,string>m;
int main(){
  m.insert(make_pair("hello","你好"));
  TcpSer ts;
  Judge(ts.InitTcp());
  Judge(ts.Mbind());
  Judge(ts.Mlisten());
  int epfd= epoll_create(2);
  struct epoll_event ee;
  ee.events=EPOLLIN;
  ee.data.fd=ts.Getfd();

  epoll_ctl(epfd,EPOLL_CTL_ADD,ts.Getfd(),&ee);

  while(1){
    struct epoll_event es[10];
    int ret = epoll_wait(epfd,es,sizeof(es),-1);
    if(ret<0){
      continue;
    }
    for(int i=0;i<ret;i++){
      if(es[i].data.fd==ts.Getfd()){
        int new_sockfd= ts.Maccept();
        if(new_sockfd<0){
          continue;
        }
        struct epoll_event ea;
        ea.events=EPOLLIN;
        ea.data.fd=new_sockfd;
        epoll_ctl(epfd,EPOLL_CTL_ADD,new_sockfd,&ea);
      }else{
        TcpSer tt;
        tt.sockset(es[i].data.fd);
        string result;
        std::string msg;
        int r_size=   tt.Mrecv(&msg);
        if(r_size==-100){
          epoll_ctl(epfd,EPOLL_CTL_DEL,es[i].data.fd,NULL);
        }
        result=(m.find(msg))->second;
        tt.Msend(result);
        tt.Mclose();
      }

    }
  }
  ts.Mclose();
  return 0;
}
